package com.sharecode.stock.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.sharecode.stock.vo.stock.StockHistory;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 获取历史数据
 * 
 * 日线
 * 
 * http://quotes.money.163.com/service/chddata.html?code=代码&start=开始时间&end=结束时间&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP
 * 
 * 参数说明：代码为股票代码，上海股票前加0，如600756变成0600756，深圳股票前加1。时间都是6位标识法，年月日，fields标识想要请求的数据。可以不变。
 * 
 * 例如大盘指数数据查询（上证指数000001前加0，沪深300指数000300股票前加0，深证成指399001前加1，中小板指399005前加1，创业板指399006前加1）：
 * http://quotes.money.163.com/service/chddata.html?code=0000300&start=20151219&end=20171108&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;VOTURNOVER
 * 
 * @author Administrator
 *
 */
@Slf4j
public class StockDataUtils {
	private static final String URL = "http://quotes.money.163.com/service/chddata.html?code=%s&start=%s";

	public static void main(String[] args) throws Exception {
		getStockHistories("0300882", "20200701");
	}

	public static List<StockHistory> getStockHistories(String code, String startDate) {
		try {
			InputStream inputStream = downLoadFromUrl(String.format(URL, code, startDate));
			CsvToBeanBuilder<StockHistory> csvToBeanBuilder = new CsvToBeanBuilder<StockHistory>(
					new InputStreamReader(inputStream, "GBK"));

			HeaderColumnNameMappingStrategy<StockHistory> strategy = new HeaderColumnNameMappingStrategy<>();
			strategy.setType(StockHistory.class);

			List<StockHistory> list = csvToBeanBuilder.withMappingStrategy(strategy).build().parse();
			log.info("获取历史数据code->{} start->{} size->{}", code, startDate, list.size());
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取历史数据异常,code:" + code + " startDate:" + startDate, e);
		}
		return null;
	}

	private static InputStream downLoadFromUrl(String urlStr) throws IOException {
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 设置超时间为3秒
		conn.setConnectTimeout(10 * 1000);
		// 防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

		return conn.getInputStream();
	}
}
